package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Code;
import com.itheima.common.MessageConstant;
import com.itheima.common.PageResult;
import com.itheima.common.Result;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @program: reggie-manager
 * @ClassName CategoryController
 * @description: //TODO 菜品、套餐分类管理-控制器
 * @author: shan
 * @create: 2022-06-05 11:13
 * @Version 1.0
 **/
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    /** @Author shan
     * @Description //TODO 分页查询
     * @Date 16:53
     * @Param
     * @return
     **/
    @GetMapping("/page")
    public PageResult page(Integer page, Integer pageSize){
        //1.调用service执行分页查询
        Page<Category> res = categoryService.page(page,pageSize);
        //2.检查分页查询结果
        if(res == null){
            return new PageResult(Code.ERROR, MessageConstant.CAT_GET_ERROR);
        }
        //3.获取当前页列表数据、总条数
        List<Category> records = res.getRecords();
        long total = res.getTotal();
        //4.封装返回结果
        return new PageResult(Code.OK, MessageConstant.CAT_GET_SUCCESS,records,total);
    }
    /** @Author shan
     * @Description //TODO 修改
     * @Date 16:54
     * @Param
     * @return
     **/
    @PutMapping
    public Result update(@RequestBody Category category){
        int row = categoryService.update(category);
        if(row<1){
            return new Result(Code.ERROR,MessageConstant.CAT_UPDATE_ERROR);
        }
        return new Result(Code.OK,MessageConstant.CAT_UPDATE_SUCCESS);
    }
    /** @Author shan
     * @Description //TODO 删除
     * @Date 16:54
     * @Param
     * @return
     **/
    @DeleteMapping
    public Result del(Long id){
        int row = categoryService.deleteById(id);
        if(row<1){
            return new Result(Code.ERROR,MessageConstant.CAT_DELETE_ERROR);
        }
        return new Result(Code.OK,MessageConstant.CAT_DELETE_SUCCESS);
    }
    /** @Author shan
     * @Description //TODO 新增
     * @Date 16:54
     * @Param
     * @return
     **/
    @PostMapping
    public Result save(@RequestBody Category category){
        int row = categoryService.save(category);
        if(row<1){
            return new Result(Code.ERROR,MessageConstant.CAT_SAVE_ERROR);
        }
        return new Result(Code.OK,MessageConstant.CAT_SAVE_SUCCESS);
    }
    /** @Author shan
     * @Description //TODO list
     * @Date 14:35
     **/

    @GetMapping("/list")
    public Result findAll(@RequestParam(value = "type",required = false) Integer type){
        List<Category> categoryList = categoryService.findAll(type);
        return new Result(Code.OK,MessageConstant.CAT_GET_SUCCESS,categoryList);
    }
}